﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Heclei.ExcelComponent;

namespace MPBBS.Common
{
    public static class OfficeHelper
    {
        public static bool ListToExcel<T>(List<T> t, string exportFileFullPath, string fileName)
        {
            int colIndex = 0;
            int rowIndex = 1;
            try
            {
                Type objType = typeof (T);
                var property = objType.GetProperties();
                var excelFile = new ExcelFile();
                var sheet = excelFile.Worksheets.Add("Export Data");
                foreach (var propertyInfo in property)
                {
                    sheet.Cells[0, colIndex++].Value = propertyInfo.Name;
                }
                colIndex = 0;
                foreach (var listItem in t)
                {
                    foreach (var propertyInfo in property)
                    {
                        object obj = objType.GetProperty(propertyInfo.Name).GetValue(listItem, null);
                        if (obj == null)
                        {
                            sheet.Cells[rowIndex, colIndex++].Value = "";
                            continue;
                        }
                        sheet.Cells[rowIndex, colIndex++].Value = obj.ToString();
                    }
                    colIndex = 0;
                    rowIndex++;
                }
                string serverPath = exportFileFullPath;
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);
                }
                string excelPath = serverPath + "\\" + fileName + ".xls";
                excelFile.SaveXls(excelPath);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}
